package com.tiance.integration.wechat;

import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.concurrent.locks.ReentrantLock;

/**
 *
 * @author 雷霆
 * @version 1.0.0
 * @date$ 2019/2/21
 *
 * Description：
 *
 * Modification History:
 *
 */
public class TokenUtil {
    private static AccessToken token    =new AccessToken();

    private static final ReentrantLock mainLock = new ReentrantLock();


    private TokenUtil() {
    }


    public static boolean isNeedUpdateAccessToken(){
        try {
            mainLock.lock();
            if(StringUtils.isEmpty(token.getAccessToken())){
                return true;
            }
            long currentTime = System.currentTimeMillis() / 1000;
            if(currentTime > (token.getStartTimeSecond() + token.getExpires_in() * 0.8)){
                return true;
            }

            return false;
        }finally {
            mainLock.unlock();
        }

    }

    public static AccessToken getToken() {
        return token;
    }

    public static String  getAccessToken() throws IOException {
        try {
            mainLock.lock();
            if(!isNeedUpdateAccessToken()){
                return token.getAccessToken();
            }
            AccessToken accessToken=WechatClient.getAccessToken();
            token=accessToken;
            return token.getAccessToken();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            mainLock.unlock();
        }

        return token.getAccessToken();
    }

    public static void setToken(AccessToken token) {
        TokenUtil.token = token;
    }
}
